/**
 * 
 */
package travibot.meta.dao.jdbctemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import travibot.engine.MaterialFactory;
import travibot.model.Cost;
import travibot.model.Material;


/**
 * @author macekpet
 *
 */
public class StructureCostsResultSetExtractor implements ResultSetExtractor {

    MaterialFactory materialFactory;
    
    /* (non-Javadoc)
     * @see org.springframework.jdbc.core.ResultSetExtractor#extractData(java.sql.ResultSet)
     */
    public Object extractData(ResultSet rs) throws SQLException, DataAccessException {

        Map<Integer, Cost> costs = new HashMap<Integer, Cost>();
        Cost cost = null;
        int lastLevel = 1;
        while (rs.next()) {
            
            Material material = materialFactory.getMaterial(rs.getInt("id_material"));
            int materialCount = rs.getInt("material_count");
            int levelValue = rs.getInt("level");
            if(levelValue != lastLevel){
                costs.put(lastLevel, cost);
                cost = new Cost();
            }
            if(cost != null)
                cost.addMaterialCost(material, materialCount);
            
            lastLevel = levelValue;
        }
        
        return costs;
    }

    
    public void setMaterialFactory(MaterialFactory materialFactory) {
    
        this.materialFactory = materialFactory;
    }
    
    

}
